#!/bin/bash
#SBATCH --nodes=1
#SBATCH --partition=gpu
#SBATCH --gres=gpu:4
#SBATCH --ntasks-per-node=96
#SBATCH --time=500:00:00
#SBATCH --job-name=equ_run

module load apps/gromacs/2020.6
module load apps/anaconda3/2021.11
source /public/software/apps/anaconda3/2021.11/bin/activate base

echo " Start equilibration"
function min_equ {
[ ! -f $1/npt.gro ] && { ( cd $1/ && gmx mdrun --deffnm npt -nt 1 > npt_mdrun_log.log 2>&1 ) || { echo "Failed to run command  at line ${LINENO}" && exit; } }
# [ ! -f $1/md_nocont.tpr ] && { gmx grompp -c $1/npt.gro -r $1/npt.gro -t $1/npt.cpt -f $1/md_nocont.mdp -po $1/mdout_nocont.mdp -o $1/md_nocont.tpr -n $1/index.ndx -p $1/system.top -maxwarn 7 > $1/mdout_nocont.log 2>&1 || { echo "Failed to run command  at line ${LINENO}" && exit; } }
[ ! -f $1/md.tpr ] && { gmx grompp -c $1/npt.gro -r $1/npt.gro -t $1/npt.cpt -f $1/md.mdp -p $1/system.top -o $1/md.tpr -n $1/index.ndx -po $1/mdout.mdp -maxwarn 7 > $1/mdout.log 2>&1 || { echo "Failed to run command  at line ${LINENO}" && exit; } }
}

n_jobs=0
max_jobs=90
pids=""

function waiting {
for pid in $1; do 
    wait $pid
done  
}

ligands=`ls ligands/*.sdf`

for lig in $ligands; do
lig_f_name=${lig:8};
lig_name=${lig_f_name%%.*};
echo ${lig_name}
min_equ ${lig_name}_md &
pids="$pids $!"
n_jobs=$((n_jobs + 1))
if (( $n_jobs > max_jobs)); then
waiting $pids
n_jobs=0
pids=""
fi
done;
waiting $pids

echo " Finished equilibration"

